/*compare.h*/

#include <cv.h>
#include <highgui.h>
#include <cxcore.h>
#include <cvaux.h>
#include <math.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>


/*
 * compare: PBH Apr 08
 * based on irismatch code by P Flynn
 * This code supports iris shifting
 *
 */

#define IMG(img,i,j) (*(unsigned char *)((img)->imageData + (i)*(img)->widthStep+ (j)))

float compareImg(IplImage * src1, IplImage * src2, bool debug = 0) 
{
  int i,j,s;


  if (!src1 || !src2) {
    fprintf(stderr,"FAIL: src1 0x%x src2 0x%x\n",src1,src2);
    exit(-1);
  }

  if ((src1->height != src2->height) || (src1->width != src2->width)) {
    fprintf(stderr,"FAIL: image size mismatch.\n");
    exit(-1);
  }

  // loop variable s is the shift
  // src1(i,j)  and src2(i,(j+s)%ncolumns) are corresponding pixels.

  float minSD = 1.0e30;
  int minshift;
  float sd = 0.0;
  for (s=0;s<src1->width;s++) //for each pixel shift --cylinder check
  {
    sd = 0.0; //start squared diff at 0
    for( i = 0 ; i < src1->height ; i++) //y
     for( j = 0 ; j < src1->width ; j++)  //x
    {
      unsigned char p1 = IMG(src1, i, j);
      unsigned char p2 = IMG(src2, i, (j+s) % (src2->width));
      sd += (p1-p2) * (p1-p2);
    }
    if (sd < minSD) 
    { 
      minSD = sd; 
      minshift = s; 
    }
  }

  if (debug)
    printf("best shift %d, min SSD %f\n", minshift, minSD);
  //printf("%10.0f\n",minSD);
 
  return minSD;
}
